package com.geo.content.service;

import com.geo.ai.model.AIRequest;
import com.geo.ai.model.AIResponse;
import com.geo.content.dto.ContentGenerationRequest;
import com.geo.content.dto.ContentGenerationResponse;
import com.geo.content.entity.MultimodalContent;
import com.geo.keyword.entity.Keyword;
import com.geo.service.ai.AiModelManager;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 内容生成服务
 * 提供基于AI的多模态内容生成功能
 * 
 * @author GEO Team
 * @version 1.0.0
 */
@Slf4j
@Service
public class ContentGenerationService {
    
    private static final Logger logger = LoggerFactory.getLogger(ContentGenerationService.class);
    
    // 内容类型常量
    public static final String ARTICLE = "ARTICLE";
    public static final String QA = "QA";
    public static final String PRODUCT_DESC = "PRODUCT_DESC";
    public static final String COMPANY_INTRO = "COMPANY_INTRO";
    public static final String SERVICE_DESC = "SERVICE_DESC";
    public static final String SOCIAL_POST = "SOCIAL_POST";
    public static final String EMAIL_TEMPLATE = "EMAIL_TEMPLATE";
    public static final String AD_COPY = "AD_COPY";
    
    @Autowired
    private AiModelManager aiModelManager;
    
    /**
     * 生成内容
     * @param request 内容生成请求
     * @return 内容生成响应
     */
    public ContentGenerationResponse generateContent(ContentGenerationRequest request) {
        logger.info("开始生成内容: 类型={}", request.getContentType());
        
        try {
            // 构建AI请求
            String prompt = buildContentPrompt(request);
            
            AIRequest aiRequest = AIRequest.builder()
                    .userInput(prompt)
                    .maxTokens(2000)
                    .temperature(0.7)
                    .build();
            
            // 调用AI模型
            AIResponse aiResponse = aiModelManager.invoke(aiRequest);
            
            if (!aiResponse.isSuccess()) {
                throw new RuntimeException("AI调用失败: " + aiResponse.getErrorMessage());
            }
            
            // 构建响应
            ContentGenerationResponse response = new ContentGenerationResponse();
            response.setContentId("content_" + System.currentTimeMillis());
            response.setTitle("生成的标题");
            response.setContent(aiResponse.getContent());
            response.setContentType(request.getContentType());
            response.setWordCount(aiResponse.getContent().length());
            
            logger.info("内容生成成功: contentId={}", response.getContentId());
            return response;
            
        } catch (Exception e) {
            logger.error("内容生成失败", e);
            throw new RuntimeException("内容生成失败: " + e.getMessage());
        }
    }
    
    /**
     * 异步生成内容
     * @param request 内容生成请求
     * @return 内容生成响应的CompletableFuture
     */
    public CompletableFuture<ContentGenerationResponse> generateContentAsync(ContentGenerationRequest request) {
        return CompletableFuture.supplyAsync(() -> generateContent(request));
    }
    
    /**
     * 批量生成内容
     * @param requests 内容生成请求列表
     * @return 内容生成响应列表
     */
    public List<ContentGenerationResponse> batchGenerateContent(List<ContentGenerationRequest> requests) {
        return requests.stream()
                .map(this::generateContent)
                .toList();
    }
    
    /**
     * 优化现有内容
     * @param contentId 内容ID
     * @param optimizationType 优化类型
     * @param merchantId 商家ID
     * @return 优化后的内容
     */
    public MultimodalContent optimizeContent(String contentId, String optimizationType, String merchantId) {
        logger.info("开始优化内容: contentId={}, 类型={}, 商家ID={}", contentId, optimizationType, merchantId);
        
        // 模拟优化过程
        MultimodalContent content = MultimodalContent.builder()
                .id(contentId)
                .title("优化后的标题")
                .textContent("优化后的内容")
                .qualityScore(90.0)
                .seoScore(85.0)
                .build();
        
        logger.info("内容优化成功: contentId={}", contentId);
        return content;
    }
    
    /**
     * 构建内容生成提示词
     */
    private String buildContentPrompt(ContentGenerationRequest request) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("请根据以下要求生成内容:\n");
        
        if (request.getTargetKeywords() != null && !request.getTargetKeywords().isEmpty()) {
            prompt.append("关键词: ").append(String.join(",", request.getTargetKeywords())).append("\n");
        }
        
        prompt.append("内容类型: ").append(request.getContentType()).append("\n");
        
        if (request.getTargetAudience() != null && !request.getTargetAudience().isEmpty()) {
            prompt.append("目标受众: ").append(request.getTargetAudience()).append("\n");
        }
        
        if (request.getWritingStyle() != null && !request.getWritingStyle().isEmpty()) {
            prompt.append("写作风格: ").append(request.getWritingStyle()).append("\n");
        }
        
        if (request.getContentLength() != null) {
            prompt.append("字数要求: ").append(request.getContentLength()).append("\n");
        }
        
        return prompt.toString();
    }
}